<?php

namespace app\api\controller;

use app\common\BaseHelper;

use app\admin\model\Product as ProductMdl;
use app\admin\model\Productcategory;
use app\admin\model\Flashsale;
use app\admin\model\Buygifts;
use app\admin\model\Repurchase;
use app\admin\model\Groupproduct;
use app\admin\model\Brand;
use app\admin\model\Productcomment;
use app\admin\model\Member;
use app\admin\model\Cookbook;
use app\admin\model\Cookbookstep;
use app\admin\model\Image;

/**
 * 商品类
 */
class Product extends Base
{

    /**
     * 热搜
     */
    public function searchKeywords()
    {
        //$param = self::getHttpParam();
        $where = [];
        $model = db('product_search');
        $field = 'keyword, count_hit';
        $order = 'count_hit DESC';
        $result = $model->where($where)->field($field)->order($order)->limit(0, 20)->select();
        if (!$result) {
            return show(config('status.ERROR_STATUS'), '没有相关数据', '没有相关数据');
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
    }

    /**
     * 搜索
     */
    public function searchProduct()
    {
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (empty($param->keyword) || !trim($param->keyword)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '关键字(keyword) 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [
            'name' => ['like', '%' . $param->keyword . '%'],
            'status' => 1,
            //'type' => 0
            'type' => ['not in', [1, 3]],
            'is_gift' => 2
        ];

        $model = new ProductMdl();
        $field = 'id, name, img_url, price, unit, spec, describe, type';
        $order = 'create_date DESC';
        $list = $model->where($where)->field($field)->order($order)->limit($start, $length)->select();
        if (!$list) {
            return show(config('status.ERROR_STATUS'), '没有相关商品', '没有相关商品');
        }

        $total = $model->where($where)->count();
        $list = $model->formatProducts($list);

        // 添加关键字到热搜表
        $searchDB = db('product_search');
        $productSearch = $searchDB->where(['keyword' => $param->keyword])->find();
        if ($productSearch) {
            //$productSearch->update(['count_hit' => 'count_hit' + 1]);
            $searchDB->where(['keyword' => $param->keyword])->setInc('count_hit');
        } else {
            $searchDB->insert([
                'create_date' => date('Y-m-d H:i:s'),
                'keyword' => $param->keyword,
                'count_hit' => 1
            ]);
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $list, $total);
    }

    /**
     * 获取商品分类
     */
    public function getCategory()
    {
        $param = self::getHttpParam();

        $where = [
            'parent_id' => 0,
            'status' => 1
        ];
        if (isset($param->parentId) && $param->parentId) {
            $where = [
                'parent_id' => $param->parentId
            ];
            $data = Productcategory::where($where)->field('id, name')->select();
        } else {
            $data = Productcategory::where($where)->field('id, name')->select();

            /*if($data){
                $child = Productcategory::where(['parent_id' => $data[0]['id']])->field('id, name')->select();
                $data[0]['childs'] = $child;
            }*/
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 获取商品列表
     */
    public function getList()
    {
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (empty($param->categoryId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '分类ID(categoryId) 不能为空');
        }
        if (empty($param->order)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '排序(order) 不能为空');
        }
        if (!in_array($param->order, [1, 2, 3])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'order 格式不正确');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }
        $where = [
            'status' => 1,
            'category_id' => $param->categoryId,
            //'type' => 0
            'type' => ['not in', [1, 3]],
            'is_gift' => 2
        ];
        /*if (!empty($param->categoryId)) {
            $where['category_id'] = $param->categoryId;
        }*/

        $model = new ProductMdl();
        $fields = 'id, name, img_url, price, unit, spec, describe, type';
        $order = 'create_date DESC';
        switch ($param->order) {
            case 1:
                // 新品
                $order = 'create_date DESC';
                break;
            case 2:
                // 销量 由高到底
                $order = 'total_sales DESC';
                break;
            case 3:
                // 价格由低到高
                $order = 'price ASC';
                break;
            default :break;
        }

        $list = $model->where($where)->field($fields)->limit($start, $length)->order($order)->select();
        if (!$list) {
            return show(config('status.ERROR_STATUS'), '没有相关商品', '没有相关商品');
        }
        $total = ProductMdl::where($where)->count();

        /*foreach ($list as &$item) {
            $unitArr = get_product_unit();
            $item['unit'] = $unitArr[$item['unit']];
            // 库存
            $qty = Stock::getStock($item['id']);
            $item['qty'] = $qty;
        }*/
        $list = $model->formatProducts($list);

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $list, $total);
    }

    /**
     * 获取活动商品（部分商品）
     */
    public function activityProducts()
    {
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (empty($param->productIds)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '商品ID集合(productIds) 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }
        $where = [
            'id' => ['in', $param->productIds],
        ];

        $model = new ProductMdl();
        $fields = 'id, name, img_url, price, unit, spec, describe, type';
        $order = 'create_date DESC';
        $list = $model->where($where)->field($fields)->limit($start, $length)->order($order)->select();
        if (!$list) {
            return show(config('status.ERROR_STATUS'), '没有相关商品', '没有相关商品');
        }
        $total = ProductMdl::where($where)->count();

        $list = $model->formatProducts($list);

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $list, $total);
    }

    /**
     * 获取商品详情
     */
    public function getDetail()
    {
        $param = self::getHttpParam();

        if (empty($param->productId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '商品ID(productId) 不能为空');
        }

        $productId = $param->productId;
        $where = [
            'id' => $productId
        ];
        $model = new ProductMdl();
        $fields = 'id, name, img_url, img_urls, price, unit, spec, describe, member_integral, brand_id, packing, address, quality_time, storage_mode, detections, cookbook_ids, status, type';
        $item = $model->where($where)->field($fields)->find();
        if (empty($item)) {
            return show(config('status.ERROR_STATUS'), '未查到相关商品', '未查到相关商品');
        }
        if ($item['status'] != 1) {
            return show(config('status.ERROR_STATUS'), '该商品已被禁用或已被删除', '该商品已被禁用或已被删除');
        }

        // 轮播图
        $item['img_urls'] = explode(',', $item['img_urls']);
        // 单位
        $unitArr = get_product_unit();
        $item['unit'] = $unitArr[$item['unit']];
        // 库存
        $item['qty'] = Stock::getStock($item['id']);
        // 品牌
        $item['brand'] = Brand::where('id', $item['brand_id'])->value('name');
        // 安心检测
        if ($item['detections']) {
            $item['detections'] = explode(',', $item['detections']);
        }
        // 详情图
        $detailImgs = Image::where(['related_id' => $productId, 'tag' => 'detail_imgs'])->field('img_url')->order('sorting ASC')->select();
        $item['detailImgs'] = $detailImgs;
        // 视频
        $videos = Image::where(['related_id' => $productId, 'tag' => 'videos'])->field('img_url')->order('sorting ASC')->select();
        $item['videos'] = $videos;

        // 商品评价
        $comments = Productcomment::where(['product_id' => $productId, 'is_delete' => 2])->field('id, create_date, member_id, score, content')->order('create_date DESC')->limit(0, 5)->select();
        $item['comments'] = $this->handleComments($comments);
        $item['countComment'] = Productcomment::where(['product_id' => $productId, 'is_delete' => 2])->field('id')->count();

        // 如果登录了，查看购物车里该商品的数量
        $cartJoin = [
            ['__PRODUCT__ p', 'p.id = a.product_id'],
            ['__STOCK__ s', 's.product_id = a.product_id']
        ];
        if(isset($param->memberId) && $param->memberId){
            $countInCart = \app\admin\model\Shoppingcart::alias('a')->where(['a.member_id' => $param->memberId, 'a.product_id' => $productId, 'a.status' => 1])->where(['p.status' => 1])->join($cartJoin)->value('count');
            $item['countInCart'] = $countInCart;
        }

        // 扫二维码不会带有参数 $param->type ，所以不能通过传递的参数来判断
        if ($item['type'] == 1) {
//            if ($param->type == 'flashsale') {
//
//            }
            //  限时特价商品
            // 当前小时
            $nowHour = date('G');
            if ($nowHour >= 7 && $nowHour < 10) {
                $time_range = 7;
            } elseif ($nowHour >= 10 && $nowHour < 13) {
                $time_range = 10;
            } elseif ($nowHour >= 13 && $nowHour < 16) {
                $time_range = 13;
            } elseif ($nowHour >= 16 && $nowHour < 19) {
                $time_range = 16;
            } elseif ($nowHour >= 19 && $nowHour < 21) {
                $time_range = 19;
            } else {
                $time_range = '';
            }
            if ($time_range) {
                $flashsaleWhere = [
                    'product_id' => $productId,
                    'status' => 1,
                    'start_time' => ['elt', date('Y-m-d H:i:s')],
                    'end_time' => ['egt', date('Y-m-d H:i:s')],
                ];
                $flashsaleWhere['effective_date'] = ['like', '%,' . $time_range . ',%'];
                $flashsaleInfo = Flashsale::where($flashsaleWhere)->field('promotion_type, promotion_discount, markup, buy_limit_type, buy_limit_num, start_time, end_time, effective_date, to_user_type, to_users, range, store_ids')->find();
                if ($flashsaleInfo) {
                    $item['promotion_type'] = $flashsaleInfo['promotion_type'];
                    $item['promotion_discount'] = $flashsaleInfo['promotion_discount'];
                    $item['buy_limit_type'] = $flashsaleInfo['buy_limit_type'];
                    $item['buy_limit_num'] = $flashsaleInfo['buy_limit_num'];
                    // 原价
                    $item['ori_price'] = $item['price'];
                    // 优惠后的价格
                    $item['price'] = $flashsaleInfo['markup'];
                    // 限购数
                    if ($flashsaleInfo['buy_limit_type'] == 1) {
                        $item['limit_num'] = 1;
                    } elseif ($flashsaleInfo['buy_limit_type'] == 2) {
                        $item['limit_num'] = 0;
                    } else {
                        $item['limit_num'] = $flashsaleInfo['buy_limit_num'];
                    }
                    $item['start_time'] = $flashsaleInfo['start_time'];
                    $item['end_time'] = $flashsaleInfo['end_time'];
                    $item['to_user_type'] = $flashsaleInfo['to_user_type'];
                    $item['to_users'] = $flashsaleInfo['to_users'];
                    $item['to_users'] && $item['to_users'] = explode(',', $item['to_users']);

                    // 结束时间的时间戳
                    $endTime = strtotime(date('Y-m-d') . ' ' . ($time_range + 2) . ':59:59');
                    $item['endTime'] = $endTime;
                } else {
                    $item['type'] = 0;
                }
            } else {
                $item['type'] = 0;
            }
        } elseif ($item['type'] == 2) {
//            if ($param->type == 'buygifts') {
//
//            }
            // 买赠商品
//            if (empty($param->gift_product_id)) {
//                return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '赠送商品ID(gift_product_id) 不能为空');
//            }
            //$buygiftInfo = Buygifts::where(['buy_product_id' => $item['id'], 'gift_product_id' => $param->gift_product_id, 'status' => 1])->field('gift_product_id, buy_num, gift_num, to_user_type, to_users, range, store_ids')->find();
            $buygiftInfo = Buygifts::where(['buy_product_id' => $productId, 'status' => 1])->field('gift_product_id, buy_num, gift_num, to_user_type, to_users, range, store_ids')->find();
            $gift_product_id = $buygiftInfo['gift_product_id'];
            if ($buygiftInfo) {
                $item['gift_product_id'] = $buygiftInfo['gift_product_id'];
                $item['buy_num'] = $buygiftInfo['buy_num'];
                $item['gift_num'] = $buygiftInfo['gift_num'];
                $item['to_user_type'] = $buygiftInfo['to_user_type'];
                $item['to_users'] = $buygiftInfo['to_users'];
                $item['to_users'] && $item['to_users'] = explode(',', $item['to_users']);
                // 赠送商品
                $giftProductInfo = $model->where('id', $item['gift_product_id'])->field('name, img_urls, price, unit')->find();
                $item['gift_product_info'] = $giftProductInfo;
                $item['gift_product_info']['unit'] = $unitArr[$item['gift_product_info']['unit']];

                // 轮播图（包含赠送的商品）
                $item['img_urls'] = array_merge($item['img_urls'], explode(',', $giftProductInfo['img_urls']));

                // 详情图（包含赠送的商品）
                $giftDetailImgs = Image::where(['related_id' => $gift_product_id, 'tag' => 'detail_imgs'])->field('img_url')->order('sorting ASC')->select();
                $item['detailImgs'] = array_merge($item['detailImgs'], $giftDetailImgs);
            } else {
                $item['type'] = 0;
            }
            //$giftProductInfo = $model->where('id', $gift_product_id)->field('img_urls')->find();
        } elseif ($item['type'] == 3) {
            // 加价换购商品
            // 不能出现加价换购商品，因为购物车有可能会出现两种（一种是原价、一种是换购价）
            // 限购数量
            /*$repurchaseInfo = Repurchase::where(['product_id' => $productId, 'status' => 1])->field('markup, limit_num')->find();
            if ($repurchaseInfo) {
                $item['price'] = $repurchaseInfo['markup']; // 换购价
                $item['limit_num'] = $repurchaseInfo['limit_num'];
            }*/
        } else {
            // 是否是拼团商品
            $groupproductInfo = Groupproduct::where(['product_id' => $productId, 'status' => 1, 'start_time' => ['elt', time()], 'end_time' => ['egt', time()]])->field('group_price, group_succ_count, group_succ_time, confine_count')->find();
            if ($groupproductInfo) {
                $item['group_price'] = $groupproductInfo['group_price'];
                $item['group_succ_count'] = $groupproductInfo['group_succ_count'];
                $item['group_succ_time'] = $groupproductInfo['group_succ_time'];
                $item['confine_count'] = $groupproductInfo['confine_count'];
                $item['type'] = 4;
            }
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    /**
     * 商品详情 - 菜谱
     */
    public function getCookbooks()
    {
        $param = self::getHttpParam();

        if (empty($param->productId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '商品ID(productId) 不能为空');
        }

        $cookbookIds = ProductMdl::where(['id' => $param->productId])->value('cookbook_ids');
        $where = [
            'id' => ['in', $cookbookIds]
        ];
        $model = new Cookbook();
        $fields = 'id, name, img_url';
        $order = '';
        $item = $model->where($where)->order($order)->field($fields)->select();
        if (!$item) {
            return show(config('status.ERROR_STATUS'), '未查到商品信息', '未查到商品信息');
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    /**
     * 商品详情 - 菜谱详情
     */
    public function getCookbookDetail()
    {
        $param = self::getHttpParam();

        if (empty($param->id)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '菜谱ID(id) 不能为空');
        }

        $where = [
            'id' => ['in', $param->id]
        ];
        $model = new Cookbook();
        $fields = 'id, name, img_url, introduction, ingredients';
        $order = '';
        $item = $model->where($where)->order($order)->field($fields)->find();
        if (!$item) {
            return show(config('status.ERROR_STATUS'), '没有相关商品', '没有相关商品');
        }

        // 食材
        $item['ingredients'] = json_decode($item['ingredients'], true);
        // 烹饪步骤
        $cookbookSteps = Cookbookstep::where(['cookbook_id' => $param->id])->order('sort ASC')->select();
        $item['cookbookSteps'] = $cookbookSteps;

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    /**
     * 商品详情 - 评价
     */
    public function getComments()
    {
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (empty($param->productId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '商品ID(productId) 不能为空');
        }

        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $productId = $param->productId;
        $where = [
            'product_id' => $productId,
            'is_delete' => 2
        ];
        if (!empty($param->productId)) {
            if (!in_array($param->type, [0, 1, 2, 3])) {
                return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
            }
            switch($param->type){
                case 1:
                    // 好评 4星及以上
                    $where['score'] = ['egt', 4 * 20];
                    break;
                case 2:
                    // 中评 2-3星
                    $where['score'] = ['between', '40,60'];
                    break;
                case 3:
                    // 差评 1星
                    $where['score'] = ['elt', 20];
                    break;
                default : break;
            }
        }

        $model = new Productcomment();
        $fields = 'id, create_date, member_id, score, content';
        $order = 'create_date DESC';
        $list = $model->where($where)->order($order)->field($fields)->limit($start, $length)->select();
        if (!$list) {
            return show(config('status.SUCCESS_STATUS'), '', []);
        }
        $total = $model->where($where)->count();
        $list = $this->handleComments($list);

        // 好评数
        unset($where['score']);
        $countTotal = $model->where($where)->count();
        $countLevel1 = $model->where($where)->where(['score' => ['egt', 80]])->count();
        $countLevel2 = $model->where($where)->where(['score' => ['between', '40,60']])->count();
        $countLevel3 = $model->where($where)->where(['score' => ['elt', 20]])->count();

        $data = [
            'list' => $list,
            'total' => $total,
            'countTotal' => $countTotal,
            'countLevel1' => $countLevel1,
            'countLevel2' => $countLevel2,
            'countLevel3' => $countLevel3,
        ];

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 商品评价列表
     */
    protected function handleComments($data)
    {
        if(!$data){
            return $data;
        }

        foreach ($data as $item) {
            $memberInfo = Member::where(['id' => $item['member_id']])->field('name, avatar')->find();
            $item['memberName'] = $memberInfo['name'];
            $item['memberAvatar'] = $memberInfo['avatar'];
            // 评论图片
            $imgUrls = Image::where(['related_id' => $item['id']])->order('sorting ASC')->select();
            $item['img_urls'] = $imgUrls;

            // 回复
            $item['responds'] = Productcomment::where(['responder_id' => $item['id']])->field('create_date, content')->find();
        }

        return $data;
    }

}